﻿using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace Ast.Framework.Forms
{
    [System.ComponentModel.DesignerCategory("")]
    public class FormTabPage : TabPage
    {
        private readonly string _formType;
        private readonly IFormFactory _formFactory;
        private Form _form;

        public FormTabPage(string formType, IFormFactory formFactory) : base(formType)
        {
            _formType = formType;
            _formFactory = formFactory;

            // event enter
            Enter += OnEnter;
        }

        private void OnEnter(object sender, EventArgs eventArgs)
        {
            if (_form != null) return; // initialized

            var parentForm = FindForm();
            if (parentForm == null) return; // no parent

            // delay initialization of form
            _form = _formFactory.Create(_formType);
            _form.SetTabStyle().Show();
            Controls.Add(_form);

            // close form when parent form closing
            parentForm.Closing += ParentFormOnClosing;

            // event enter
            Enter -= OnEnter;
        }

        private void ParentFormOnClosing(object sender, CancelEventArgs cancelEventArgs)
        {
            _form.Close();
        }
    }
}